//  接收url， 返回字符串

import HttpRequest from "./httpRequest";

interface HttpMessage {
  method: string;
  host: string;
  path: string;
  port: string;
  header?: {
    [propName: string]: any;
  };
  body?: {
    [propName: string]: any;
  };
  bodyText?: string;
}

function parseURL(url: string): HttpMessage {
  // 目前仅仅解析host , port 和 path
  const httpMessage: HttpMessage = {
    method: "GET",
    host: /[0-9]+\.[0-[0-9]+\.[0-9]+\.[0-9]+/.exec(url)
      ? /[0-9]+\.[0-[0-9]+\.[0-9]+\.[0-9]+/.exec(url)[0]
      : "",
    path: /\/[/a-z-_.0-9]+/i.exec(url) ? /\/[/a-z-_.0-9]+/i.exec(url)[0] : "/",
    port: /:[0-9]+/.exec(url) ? /:[0-9]+/.exec(url)[0].slice(1) : "8000",
  };

  return httpMessage;
}

// 根据获得url，发送http请求， 并返回文本字符串
export default async function request(url: string) {
  // pasreURL，生成http报文
  // 生成httpRequst对象

  const httpRequest = new HttpRequest(parseURL(url));

  // 发送Http请求
  await httpRequest.send();

  // Http响应报文主体
  const text = httpRequest.responseMessage.body;
  return text;
}
